package interceptor;


import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.env.Environment;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import component.HttpClient;
import dto.StatusDto;
import pojo.Merchant;
import util.JsonUtil;

public class VerifyInterceptor implements HandlerInterceptor{
	
	 @Resource
	 Environment env;
	 @Resource(name="jerseyClient")
	 HttpClient httpClient;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {
        Merchant merchant = (Merchant) req.getSession().getAttribute("user");
        String name = merchant.getName();
        StatusDto statusDto = new StatusDto();
        try {
//            String status = HttpUtil.getResponseStr("/admins/m/status/get?name=" + name);
        	System.out.println(env.getProperty("get.status.url")+name);
        	
        	String status =httpClient.get(env.getProperty("get.status.url")+name);
            System.out.println("status == " + status);
            statusDto = (StatusDto) JsonUtil.toJsonObject(status, StatusDto.class);
        } catch (Exception e) {
        	e.printStackTrace();
            PrintWriter writer = resp.getWriter();
            writer.write("http error!");
        }

        if (StatusDto.WHITE_LIST.equals(statusDto.getStatus())) {
          return true;
        } else if (StatusDto.WAIT_AUDIT.equals(statusDto.getStatus()) || StatusDto.BLACK_LIST.equals(statusDto.getStatus())) {
            req.setAttribute("statusInfo", statusDto.getStatus());
            req.getRequestDispatcher("/WEB-INF/merchant/refresh.jsp").forward(req, resp);
        } else if (StatusDto.REJECT.equals(statusDto.getStatus())){
            req.setAttribute("statusInfo", statusDto.getStatus());
            req.setAttribute("message", statusDto.getMessage());
            req.getRequestDispatcher("/WEB-INF/merchant/refresh.jsp").forward(req, resp);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
